const jwt = require('jsonwebtoken');
const createError = require('http-errors');
require('dotenv').config();
type Terr = any;
interface Ipayload {
  id: number;
  email: string;
  name: string;
  password?: string;
  posts: Array<string>
  [key: string]: any
}
type TsignAccessToken = (payload:Ipayload) => Promise<string>;
type TverifyAccessToken = (payload:string) => Promise<Ipayload>;
interface IjwtHandler {
  signAccessToken: TsignAccessToken;
  verifyAccessToken: TverifyAccessToken;
}
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET
const jwtHandler: IjwtHandler = {
  signAccessToken(payload: Ipayload){
    return new Promise((resolve, reject) => {
      jwt.sign({ payload, }, accessTokenSecret, {
        expiresIn: 60, // 时效 (秒)
      }, (err: Terr, token: string) => {
        if (err) {
          reject(createError.InternalServerError())
        }
        resolve(token)
      })
    })
  },
  verifyAccessToken(token: string){
    return new Promise((resolve, reject) => {
      jwt.verify(token, accessTokenSecret, (err: Terr, payload: Ipayload) => {
        if (err) {
          const message = err.name == 'JsonWebTokenError' ? 'Unauthorized' : err.message
          return reject(createError.Unauthorized(message))
        }
        resolve(payload)
      })
    })
  }
}
export type {
  Ipayload
}
export default jwtHandler;
